package com.light.netty.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class UdpBusinessServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    /**
     * 直接发送文本消息
     * @param ctx
     * @param packet
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        // 获取接收到的消息内容（字符串）
        String msg = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println("收到客户端消息: " + msg);

        // 构建响应消息
        String response = "UDP receive acc: " + msg;


        // 将响应转换为 ByteBuf 并发送回客户端
        ByteBuf responseBuf = Unpooled.copiedBuffer((response).getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(new DatagramPacket(
                responseBuf,
                packet.sender() // 客户端地址信息
        )).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("UDP Server Message sent successfully");
            } else {
                System.err.println("UDP Server Failed to send message: " + future.cause());
            }
        });
    }
}